package org.example.server.tcp;

import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;
import org.example.enums.ProtocolMessageTypeEnum;
import org.example.model.RpcRequest;
import org.example.model.RpcResponse;
import org.example.protocol.ProtocolMessage;
import org.example.protocol.ProtocolMessageDecoder;
import org.example.protocol.ProtocolMessageEncoder;
import org.example.registry.LocalRegistry;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @description TODO
 * @author sats@jz
 * @date 2025年01月10日 21:57
 */
public class TcpServerHandler implements Handler<NetSocket> {
    @Override
    public void handle(NetSocket netSocket) {
//        new TcpBufferHandlerWrapper(new Handler<Buffer>() {
//            @Override
//            public void handle(Buffer buffer) {
//
//            }
//        })
        // 解释下面的代码

        TcpBufferHandlerWrapper tcpBufferHandlerWrapper = new TcpBufferHandlerWrapper(buffer -> {
            ProtocolMessage<RpcRequest> protocolMessage;
            try {
                protocolMessage = (ProtocolMessage<RpcRequest>) ProtocolMessageDecoder.decoder(buffer);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            RpcRequest rpcRequest = protocolMessage.getBody();

            RpcResponse rpcResponse = new RpcResponse();
            Class<?> implClass = LocalRegistry.get(rpcRequest.getServiceName());
            Method method = null;
            try {
                method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
                Object result = method.invoke(implClass.getConstructor().newInstance(), rpcRequest.getArgs());
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");

            } catch (Exception e){
                e.printStackTrace();
                rpcResponse.setMessage(e.getMessage());
                rpcResponse.setException(e);
            }
            // 发送响应，编码
            ProtocolMessage.Header header = protocolMessage.getHeader();
            header.setMessageType((byte) ProtocolMessageTypeEnum.RESPONSE.getKey());
            ProtocolMessage<RpcResponse> rpcResponseProtocolMessage = new ProtocolMessage<>(header, rpcResponse);
            try {
                Buffer encoderBuffer = ProtocolMessageEncoder.encoder(rpcResponseProtocolMessage);
                netSocket.write(encoderBuffer);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
//        // 处理连接
//        netSocket.handler(buffer -> {
//
//
//
//
//        });

        netSocket.handler(tcpBufferHandlerWrapper);
    }
}
